package com.untilov.gb.me.gui;

import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import com.untilov.gb.me.GoogleBookmarksMIDlet;
import com.untilov.gb.model.FeedItem;

/**
 * List of feeds in selected category.
 * 
 * @author iuntilov
 *
 */
public class CategoryContentList extends List implements CommandListener {
    
    private GoogleBookmarksMIDlet midlet;
    
    private Command backToCategoriesCommand;

    private Command showCommand;
    
    private Vector bookmarks;

    public CategoryContentList(String title, int listType, GoogleBookmarksMIDlet midlet) {
        super(title, listType);
        this.midlet = midlet;
        // back to select category screen
        backToCategoriesCommand = new Command("Categories", Command.BACK, 1);
        this.addCommand(backToCategoriesCommand);
        // show bookmarks content
        showCommand = new Command("Show", Command.ITEM, 1);
        this.setSelectCommand(showCommand);
        this.setCommandListener(this);
    }

    public void commandAction(Command c, Displayable d) {
        if (c == backToCategoriesCommand) {
            midlet.showCategoriesList();
        } else if (c == showCommand) {
            // if something was selected
            if (getSelectedIndex() != -1) {
                midlet.showFeedDetailsForm(getSelectedFeed());
            }
        }
    }
    
    /**
     * Returns current selected feed.
     * @return selected feed
     */
    private FeedItem getSelectedFeed() {
        return (FeedItem) bookmarks.elementAt(getSelectedIndex());
    }

    /**
     * Fill list with bookmarks for selected category
     * 
     * @param category selected category
     */
    public CategoryContentList fillListForCategory(String category) {
        // clear list
        this.deleteAll();
        // select bookmarks for given category
        bookmarks = (Vector) midlet.getFeedsBuilder().
            getFeedsByCategories().get(category);
        int bookmarksSize = bookmarks.size();
        for (int i = 0; i < bookmarksSize; i++) {
            this.append(((FeedItem) bookmarks.elementAt(i)).getTitle(), null);
        }
        return this;
    }
}